package xin.cms.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xin.cms.model.Tag;
import xin.cms.repository.TagRepository;
import xin.common.http.request.NamePageRequest;
import xin.common.http.response.PageResponse;
import xin.common.http.response.PageWrapper;
import xin.common.utils.StringUtils;
import xin.core.jpa.JpaColnumConstant;
import xin.core.jpa.JpaConstant;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <pre>
 * 标签服务
 * </pre>
 *
 * @author lixin_ma@outlook.com
 * @version 1.0
 * @since 2018/8/9
 */
@Service
@Slf4j
@Transactional(readOnly = true)
public class TagService {

    @Autowired
    private TagRepository repository;

    public Tag findOne(String tagId){
        return  repository.findOne(tagId);
    }

    public PageResponse findPageList(NamePageRequest request ){
        Sort sort = new Sort(Sort.Direction.DESC,JpaColnumConstant.LAST_MODIFY_TIME);
        Pageable pageable = new PageRequest(request.getPageNumber()-1,request.getPageSize(),sort);
        Specification<Tag> specification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if(StringUtils.isNotBlank(request.getName())){
                predicates.add(criteriaBuilder.like(root.get(JpaColnumConstant.NAME),
                        JpaConstant.WILDCARD + request.getName() + JpaConstant.WILDCARD));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        return PageWrapper.wrap(repository.findAll(specification, pageable));
    }

    @Transactional
    public Tag save(Tag tag){
        return  repository.save(tag);
    }

    @Transactional
    public void delete(Tag tag){
        repository.delete(tag);
    }

}
